package com.zbkj.client.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class FileUtil {
    // 方法1：使用URI类解析（更健壮）
    public static String getExtensionWithURI(String url) {
        try {
            URL uri = new URL(url);
            String path = uri.getPath();  // 获取路径部分

            if (path == null || path.isEmpty()) {
                return "";
            }

            // 获取文件名（最后一个斜杠后的部分）
            int lastSlashIndex = path.lastIndexOf('/');
            String filename = (lastSlashIndex >= 0) ? path.substring(lastSlashIndex + 1) : path;

            // 处理带多个点的文件名（如 image.min.jpg）
            int lastDotIndex = filename.lastIndexOf('.');
            if (lastDotIndex > 0 && lastDotIndex < filename.length() - 1) {
                return filename.substring(lastDotIndex + 1);
            }

            return "";
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理高亮文本，将content中在highlight数组中存在的文字设置为高亮格式
     * @param content 原始内容
     * @param highlights 需要高亮的关键词数组
     * @return 处理后的高亮文本
     */
    public static String processHighlightText(String content, List<String> highlights) {
        System.out.println("FileUtil.processHighlightText - 输入参数: content='" + content + "', highlights=" + highlights);
        
        if (content == null || content.isEmpty() || highlights == null || highlights.isEmpty()) {
            System.out.println("FileUtil.processHighlightText - 参数为空，直接返回原内容");
            return content;
        }

        String result = content;

        // 按照关键词长度倒序排列，避免短词替换影响长词
        highlights.sort((a, b) -> b.length() - a.length());
        System.out.println("FileUtil.processHighlightText - 排序后的highlights: " + highlights);

        for (String highlight : highlights) {
            if (highlight != null && !highlight.trim().isEmpty()) {
                String beforeReplace = result;
                // 使用字符串替换
                String highlightFormat = "{\\\\1c&&}" + highlight + "{\\\\1c}";
                result = result.replace(highlight, highlightFormat);
                System.out.println("FileUtil.processHighlightText - 替换 '" + highlight + "': '" + beforeReplace + "' -> '" + result + "'");
            }
        }

        System.out.println("FileUtil.processHighlightText - 最终结果: '" + result + "'");
        return result;
    }

    /**
     * 通过读取文件流获取网络文件的真实后缀
     * @param urlString 网络文件URL
     * @return 文件真实后缀（不带点），如果无法识别则返回空字符串
     */
    public static String getRealFileExtensionFromUrl(String urlString) {
        if (urlString == null || urlString.trim().isEmpty()) {
            return "";
        }

        HttpURLConnection connection = null;
        InputStream inputStream = null;
        
        try {
            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            
            // 设置请求头，模拟浏览器访问
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(30000); // 10秒连接超时
            connection.setReadTimeout(30000);    // 10秒读取超时
            connection.setRequestProperty("User-Agent", 
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            
            // 只读取前几个字节来判断文件类型
            connection.setRequestProperty("Range", "bytes=0-1023");
            
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_PARTIAL) {
                System.out.println("HTTP请求失败，响应码: " + responseCode);
                return "";
            }
            
            // 首先尝试从Content-Type获取文件类型
            String contentType = connection.getContentType();
            if (contentType != null) {
                String extensionFromContentType = getExtensionFromContentType(contentType);
                if (!extensionFromContentType.isEmpty()) {
                    System.out.println("从Content-Type获取文件类型: " + contentType + " -> " + extensionFromContentType);
                    return extensionFromContentType;
                }
            }
            
            // 读取文件头部字节来判断文件类型
            inputStream = connection.getInputStream();
            byte[] header = new byte[32]; // 读取前32个字节
            int bytesRead = inputStream.read(header);
            
            if (bytesRead > 0) {
                String extension = getExtensionFromFileHeader(header, bytesRead);
                if (!extension.isEmpty()) {
                    System.out.println("从文件头部获取文件类型: " + extension);
                    return extension;
                }
            }
            
            log.error("无法从文件流识别文件类型，尝试从URL路径获取, 图片地址：{}", urlString);
            // 如果无法从文件头识别，最后尝试从URL路径获取
            return getExtensionWithURI(urlString);
            
        } catch (IOException e) {
            log.error("读取网络文件 {} 失败: " + e.getMessage(), urlString);
            // 发生异常时，尝试从URL路径获取
            return getExtensionWithURI(urlString);
        } finally {
            // 关闭资源
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    System.err.println("关闭输入流失败: " + e.getMessage());
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * 根据Content-Type获取文件扩展名
     * @param contentType HTTP响应的Content-Type
     * @return 文件扩展名
     */
    private static String getExtensionFromContentType(String contentType) {
        if (contentType == null) {
            return "";
        }
        
        // 移除参数部分（如charset=utf-8）
        String mimeType = contentType.split(";")[0].trim().toLowerCase();
        
        Map<String, String> mimeToExtension = new HashMap<>();
        
        // 图片类型
        mimeToExtension.put("image/jpeg", "jpg");
        mimeToExtension.put("image/jpg", "jpg");
        mimeToExtension.put("image/png", "png");
        mimeToExtension.put("image/gif", "gif");
        mimeToExtension.put("image/bmp", "bmp");
        mimeToExtension.put("image/webp", "webp");
        mimeToExtension.put("image/svg+xml", "svg");
        mimeToExtension.put("image/tiff", "tiff");
        mimeToExtension.put("image/x-icon", "ico");
        
        // 视频类型
        mimeToExtension.put("video/mp4", "mp4");
        mimeToExtension.put("video/avi", "avi");
        mimeToExtension.put("video/quicktime", "mov");
        mimeToExtension.put("video/x-msvideo", "avi");
        mimeToExtension.put("video/x-flv", "flv");
        mimeToExtension.put("video/webm", "webm");
        mimeToExtension.put("video/3gpp", "3gp");
        mimeToExtension.put("video/x-ms-wmv", "wmv");
        
        // 音频类型
        mimeToExtension.put("audio/mpeg", "mp3");
        mimeToExtension.put("audio/mp3", "mp3");
        mimeToExtension.put("audio/wav", "wav");
        mimeToExtension.put("audio/x-wav", "wav");
        mimeToExtension.put("audio/aac", "aac");
        mimeToExtension.put("audio/ogg", "ogg");
        mimeToExtension.put("audio/flac", "flac");
        
        // 文档类型
        mimeToExtension.put("application/pdf", "pdf");
        mimeToExtension.put("application/msword", "doc");
        mimeToExtension.put("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx");
        mimeToExtension.put("application/vnd.ms-excel", "xls");
        mimeToExtension.put("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx");
        mimeToExtension.put("application/vnd.ms-powerpoint", "ppt");
        mimeToExtension.put("application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx");
        
        // 压缩文件
        mimeToExtension.put("application/zip", "zip");
        mimeToExtension.put("application/x-rar-compressed", "rar");
        mimeToExtension.put("application/x-7z-compressed", "7z");
        
        // 文本类型
        mimeToExtension.put("text/plain", "txt");
        mimeToExtension.put("text/html", "html");
        mimeToExtension.put("text/css", "css");
        mimeToExtension.put("text/javascript", "js");
        mimeToExtension.put("application/json", "json");
        mimeToExtension.put("application/xml", "xml");
        
        return mimeToExtension.getOrDefault(mimeType, "");
    }

    /**
     * 根据文件头部字节判断文件类型
     * @param header 文件头部字节数组
     * @param length 实际读取的字节数
     * @return 文件扩展名
     */
    private static String getExtensionFromFileHeader(byte[] header, int length) {
        if (header == null || length < 2) {
            return "";
        }
        
        // 转换为十六进制字符串便于比较
        StringBuilder hex = new StringBuilder();
        for (int i = 0; i < Math.min(length, 16); i++) {
            hex.append(String.format("%02X", header[i] & 0xFF));
        }
        String hexString = hex.toString();
        
        // 图片文件魔数
        if (hexString.startsWith("FFD8FF")) {
            return "jpg";
        }
        if (hexString.startsWith("89504E47")) {
            return "png";
        }
        if (hexString.startsWith("474946")) {
            return "gif";
        }
        if (hexString.startsWith("424D")) {
            return "bmp";
        }
        if (hexString.startsWith("52494646") && length >= 12) {
            // RIFF格式，需要进一步判断
            String riffType = new String(header, 8, 4);
            if ("WEBP".equals(riffType)) {
                return "webp";
            }
            if ("AVI ".equals(riffType)) {
                return "avi";
            }
            if ("WAVE".equals(riffType)) {
                return "wav";
            }
        }
        
        // 视频文件魔数
        if (length >= 8) {
            // MP4文件通常在第4-7字节有ftyp标识
            if (length >= 8 && hexString.substring(8, 16).equals("66747970")) {
                return "mp4";
            }
        }
        if (hexString.startsWith("464C56")) {
            return "flv";
        }
        if (hexString.startsWith("1A45DFA3")) {
            return "webm";
        }
        
        // 音频文件魔数
        if (hexString.startsWith("494433") || hexString.startsWith("FFFB") || hexString.startsWith("FFF3")) {
            return "mp3";
        }
        if (hexString.startsWith("664C6143")) {
            return "flac";
        }
        if (hexString.startsWith("4F676753")) {
            return "ogg";
        }
        
        // 文档文件魔数
        if (hexString.startsWith("25504446")) {
            return "pdf";
        }
        if (hexString.startsWith("504B0304")) {
            return "zip"; // 也可能是docx, xlsx, pptx等基于zip的格式
        }
        if (hexString.startsWith("D0CF11E0A1B11AE1")) {
            return "doc"; // 也可能是xls, ppt等老版本Office文件
        }
        if (hexString.startsWith("526172211A0700")) {
            return "rar";
        }
        if (hexString.startsWith("377ABCAF271C")) {
            return "7z";
        }
        
        return "";
    }
}
